﻿$(document).ready(function() {

    // DOM
    var $aside = $('.aside');
    var $tabs = $('#nav-tab');
    var $tabContent = $('#nav-tabContent');
    var $homeTab = $tabs.find('a[aria-controls="nav-home"]');
    var $homeTabContent = $tabContent.find('#nav-home').clone().html('<div class="loading"> <i class="icon SkyUI icon-reload"></i> </div>');
    var tabs = [];

    var Uid = function() {
        this.uid = 0;

        this.getId = function() {
            this.uid++;
            return this.uid;
        }
    };

    // methods

    var deepCopy = function(obj) {
        var _obj = JSON.stringify(obj);
        return JSON.parse(_obj);
    };

    var toggleChildeNav = function($headItem) {
        var count = 1;
        var $childNav = $headItem.find("> .nav");
        return function(e) {
            if (count % 2 === 0)
                $childNav.addClass('d-none');
            else
                $childNav.removeClass('d-none');
            count++;
            e.stopPropagation();
        }
    };

    var closeTab = function(identify, e) {
        if (e) e.stopPropagation();

        $('#nav-tab #nav-' + identify + '-tab').remove();
        $('#nav-tabContent #nav-' + identify).remove();
        $('#nav-tab a:last-child').tab('show');
    }

    var addTabTitle = function(identify, title) {
        // init tab props
        var $newTab = $homeTab.clone();
        $newTab.removeClass('active');
        $newTab.attr('aria-selected', 'false');
        $newTab.attr('href', '#nav-' + identify);
        $newTab.attr('id', 'nav-' + identify + '-tab');
        $newTab.attr('aria-controls', 'nav-' + identify);
        $newTab.text('');

        // create close icon
        var iconClose = document.createElement('i');
        iconClose.setAttribute('class', 'icon SkyUI icon-close');
        iconClose.addEventListener('click', closeTab.bind({}, identify));
        //icon.on('click', { identify: identify }, closeTab);

        $newTab.append(iconClose);
        $newTab.append(title);

        $newTab.on('click', function(e) {
            if (e) e.preventDefault();
            $(this).tab('show');
        });

        $tabs.append($newTab);
    };

    var addPage = function($container, route, id, callback) {
        $container.load(route, function(e) {
            $container.html(e);
            bindRouteLink('#' + id);
            if (typeof callback === 'function')
                callback();
        });
    };

    var addTabContent = function(identify, route) {
        var id = 'nav-' + identify;
        var $newTabContent = $homeTabContent.clone();
        $newTabContent.removeClass('active');
        $newTabContent.attr('aria-labelledby', 'nav-' + identify + '-tab');
        $newTabContent.attr('href', '#' + identify);
        $newTabContent.attr('id', id);
        $newTabContent.attr('data-url', route);
        addPage($newTabContent, route, id);
        $tabContent.append($newTabContent);
    };

    var bindRouteLink = function(bindSection) {
        $(bindSection + ' a[data-route]').click(function() {
            var $navLink = $(this);
            var route = $navLink.attr('data-route');
            var title = $navLink.text();

            if (route) {
                var id = uid.getId();
                // add Tab
                addTabTitle(id, title);

                addTabContent(id, route);

                $('#nav-tab a:last-child').tab('show');
            }
        });
    };

    var dataToUrlParams = function(params) {
        var paramsHash = '?';
        if (params && params instanceof Array) {
            for (var i = 0; i < params.length; i++) {
                for (var key in params[i]) {
                    var str = key + '=' + params[i][key] + '&';
                    paramsHash += str ? str : '';
                }
            }
        }

        return paramsHash;
    };

    // Init Page

    var uid = new Uid();

    bindRouteLink('#nav-home');

    // init  Menu

    var menuRoute = '/home/menu';

    $aside.load(menuRoute, function() {
        var $asideNavLinks = $('.aside .head-item .nav-link');
        $asideNavLinks.each((index, elem) => {
            var $headItem = $(elem.parentElement);
            $headItem.click(toggleChildeNav($headItem));
        });
        bindRouteLink('#menu');
    });

    // Global API

    var Tab = function() {

    };

    Tab.prototype.reloadTab = function(currentTab, params) {

        var $content = $(currentTab).parent();
        var route = $content.attr('data-url');
        var id = $content.attr('id');
        var urlParams = null;
        if (params)
            urlParams = dataToUrlParams(params);

        // 因为modal关闭时间比刷新慢，延迟500ms
        // 用于解决刷新时odal还未关闭m造成的浮层挡住页面的bug
        setTimeout(function() {
            addPage($content, route + (urlParams || ''), id);
        }, 500);

    };

    Tab.prototype.close = function($elem) {
        var id = $elem.parent().attr('href').substring(1);
        closeTab(id);
    }

    window.$tab = new Tab();

});